<template>
	<view :class="bgColor" class="page-box">
		<view class="novel-detail-page" @touchstart="tchStart" @touchend="tchEnd" @click="showMenu">
			<view class="novel-title" :style="{paddingLeft: `${paddinglr}px`}">
				<p>{{chapter}}</p>
			</view>

			<view class="read-content" :style="{height: contentHeight + 'px'}">
				<view class="read-main" :style="{top: -contentHeight * currentPage + 'px', fontSize: fontSize + 'rpx', padding: `0 ${paddinglr}px`, lineHeight: lineHeight + 'px'}" v-html="nodes"></view>
				
			</view>
			<view class="blank-view">
			</view>
			<view class="footer-view" :style="{padding: `0 ${paddinglr}px`}">
				<text>{{currentPage + 1}}/{{totalPage}}</text>
				<text></text>
			</view>

		</view>	
		<view>
			<uni-popup ref="top">
				<view class="flex-btw top-popup-box" :class="bgColorPopup">
					<view class="top-popup-view" @click="goBack">
						<uni-icons type="arrowleft" size="24"></uni-icons>
					</view>
					<view class="top-popup-view ctrl-btn-boxs">
						<view class="add-shelf-btn" v-show="!isshelf" @click="addShelf">加入书架</view>
						<view @click="showAbout">
							<uni-icons type="more-filled" size="24"></uni-icons>
						</view>
					</view>
					
				</view>
				<view v-show="isAbout" class="about-box" :class="bgColorPopup">
					<view class="flex-btw about-box-top">
						<view class="flex-btw">
							<image :src="novelImg" class="book-small-image"></image>
							<view>{{novelName}}</view>
						</view>
						<view class="detail-btn" @click="toDetail">详情</view>
					</view>
					<view class="flex-btw-center">
						<view class="width-25">
							<uni-icons type="paperplane" size="24"></uni-icons>
							<view>分享本章</view>
						</view>
						<view class="width-25">
							<uni-icons type="flag" size="24"></uni-icons>
							<view>添加书签</view>
						</view>
						<view class="width-25">
							<uni-icons type="sound" size="24"></uni-icons>
							<view>更新提醒</view>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>

		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="buttom" @change="change">
				<!-- 菜单项 -->
				<view class="menu-box" :class="bgColorPopup">
					<view class="flex menu-chapter">
						<view @click="toPrevOrNextChapter(0, false)">上一章</view>
						<view @click="toPrevOrNextChapter(1)">下一章</view>
					</view>
					<view class="flex">
						<view @click="toChapter">
							<uni-icons type="list" size="20"></uni-icons>
							<view class="menu-word">目录</view>
						</view>
						<view>
							<uni-icons type="star" size="20"></uni-icons>
							<view class="menu-word">夜间</view>
						</view>
						<view @click="showSet">
							<uni-icons type="gear" size="20"></uni-icons>
							<view class="menu-word">设置</view>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
		
		<!-- 设置 -->
		<view v-show="isSet" class="set-box" :class="bgColorPopup">
			<view class="flex-btw-center set-box-view">
				<view class="flex-btw-center">
					<view class="add-sub" @click="subFontsize">A-</view>
					<view class="font-size-show">{{fontSize}}</view>
					<view class="add-sub" @click="addFontsize">A+</view>
				</view>
				<view>字体</view>
			</view>
			
			
			<view class="flex-btw-center set-box-view">
				<view :class="[item.class, item.checked ? item.borderclass : '']" class="bg-box" v-for="item, index in bgColorList" :key="index" @click="selectBg(index)" ></view>
			</view>
			
			<view class="flex-btw-center set-box-view">
				<view>
					<uni-icons type="eye" size="20"></uni-icons>
					<view class="menu-word">护眼模式</view>
				</view>
				<view>
					<uni-icons type="loop" size="20"></uni-icons>
					<view class="menu-word">自动阅读</view>
				</view>
				<view @click="toMoreSet">
					<uni-icons type="more-filled" size="20"></uni-icons>
					<view class="menu-word">更多</view>
				</view>
			</view>
			
		</view>
		
	</view>
</template>

<script>
	import _tool from '@/util/tool.js'
	
	export default {
		data() {
			return {
				isprev: false,
				
				deviceId: '',
				isshelf: 0,
				novelName: '',
				novelImg: '',
				chapter: '',
				nid: 0,
				currentChapter: 1,
				
				isinit: true,
				paddinglr: 16,
				lineHeight: 20,
				fontSize: 28,
				
				isSet: false,
				isAbout: false,
				ismenu: false,
				
				pageHeight: 0,
				contentHeight: 0,
				currentPage: 0,
				novelHeight: 0,
				totalPage: 0,

				startData: [],
				bgColor: 'bg-eye',
				bgColorPopup: 'bg-eye-weilan',
				bgColorList: [{
						name: '白色',
						class: 'bg-white',
						popupclass: 'bg-white-bai',
						borderclass: 'bg-white-bd',
						checked: false
					},
					{
						name: '浅黄',
						class: 'bg-light-yellow',
						popupclass: 'bg-ly-huang',
						borderclass: 'bg-light-yellow-bd',
						checked: false
					},
					{
						name: '护眼',
						class: 'bg-eye',
						popupclass: 'bg-eye-weilan',
						borderclass: 'bg-eye-bd',
						checked: true
					},
				],


				nodes: ''
			}
		},
		async onLoad(options) {
			uni.showLoading({
				title: '...'
			})
			/*
				三种来源，1是书架来的，2是目录来的，3是详情页
				参数有两个，1、nid，2、source（是否目录）
				通过书架和详情来的，都要通过nid获取阅读历史记录，获取读到哪里了
				从目录来的，带有章节信息，可以根据章节信息，直接返回内容。
			*/
			this.nid = options.nid
			
			// 获取小说信息
			const info = uni.getSystemInfoSync()
			this.deviceId = info.deviceId
			const novelObj = await this.myApi({
				url: '/api/novelmsg',
				data: {nid: options.nid, deviceId: this.deviceId},
				domain: true
			})
			
			if(novelObj.status == 10010) {
				uni.showToast({
					title: '没有这本小说',
					icon: 'error'
				})
				uni.hideLoading()
				return
			}
			
			
			
			// 判断是哪里来的
			if(options.source == 0) {
				// 来自详情或者书架
				// 根据历史记录，获取内容
				var url = '/api/historyandchapter'
				var data = {nid: options.nid, deviceId: this.deviceId}
				
			} else {
				// 目录
				// 根据目录，获取内容，
				
				var url = '/api/chapterone'
				var data = {cid: options.cid}
			}
			
			const chapterOne = await this.myApi({
				url: url,
				data: data,
				domain: true
			})
			
			// 获取内容
			// 查询小说是否已经在书架了
			
			// 加入书架要准备的信息
			// 1.书id，2设备id
			
			// 添加历史记录要准备的信息
			// 1.书id，2.设备id，3.章节id，4.当前页码
			
			
			this.bgColor = uni.getStorageSync('bgColor') ? uni.getStorageSync('bgColor') : this.bgColor
			this.bgColorPopup = uni.getStorageSync('bgColorPopup') ? uni.getStorageSync('bgColorPopup') : this.bgColorPopup
			this.fontSize = uni.getStorageSync('fontSize') ? uni.getStorageSync('fontSize') : this.fontSize
			// console.log(uni.getStorageSync('fontSize'))
			
			
			if (chapterOne.status == 10010) {
				uni.showToast({
					title: '出问题了！',
					icon: 'error'
				})
				uni.hideLoading()
				return
			}
			await this.getLineAndPadding()

			this.nodes = await this.getNovelContent(chapterOne.data.url)
			
			
			this.currentPage = chapterOne.data.page
			this.currentChapter = chapterOne.data.sort
			this.chapter = chapterOne.data.chapter
			this.cid = chapterOne.data.id
			
			this.novelName = novelObj.data.name
			this.novelImg = novelObj.data.img
			this.isshelf = novelObj.data.isshelf
			uni.hideLoading()
			
		},
		async onReady() {
			
		},
		onShow() {
			// 设置行距和边距时有用到
			this.getLineAndPadding()
		},
		updated: function () {
			// 避免多次操作
			this.calPageHeightAndCount()
		},
		beforeDestroy: function () {
			// 缓存配置
			uni.setStorageSync('bgColor', this.bgColor)
			uni.setStorageSync('bgColorPopup', this.bgColorPopup)
			uni.setStorageSync('fontSize', this.fontSize)
			
			
			this.myApi({
				url: '/api/addhistory',
				domain: true,
				data: {deviceId: this.deviceId, nid: this.nid, cid: this.cid, page: this.currentPage}
			})
		},
		methods: {
			toDetail() {
				this.isAbout = false
				this.closePopup()
				uni.navigateTo({
					url: '../books/books-introduce?id=' + this.nid
				})
			},
			
			// 加入书架
			addShelf() {
				this.myApi({
					url: '/api/addshelf',
					domain: true,
					data: {id: this.nid, deviceId: this.deviceId},
					method: 'POST'
				}).then((res)=>{
					if (res.status == 10001) {
						this.isshelf = 1
						uni.showToast({
							title: '加入成功'
						})
					}
				})
			},
			
			
			// 上或下一章，0是上一章，1是下一章
			async toPrevOrNextChapter(flag, isFirst = true) {
				if(this.currentChapter == 1 && flag == 0) {
					await uni.showToast({
						title: '当前已是第一章！',
						icon: 'none',
						duration: 1500
					})
					return
				}
				uni.showLoading({
					title: '...'
				})
				const chapterMsg = await this.myApi({
					url: '/api/prevornextchapter',
					domain: true,
					// 需要修改nid
					data: {flag: flag, sort: this.currentChapter, nid: this.nid}
				})
				
				if(chapterMsg.status == 10010) {
					uni.hideLoading()
					await uni.showToast({
						title: '当前已是最后一章！',
						icon: 'none',
						duration: 1500
					})
					return
				}
				// 获取，截取并赋值
				this.nodes =  await this.getNovelContent(chapterMsg.data.url)
				uni.hideLoading()
				// 重新赋值：当前章节、页码、章节
				this.currentChapter = chapterMsg.data.sort
				this.chapter = chapterMsg.data.chapter
				this.cid = chapterMsg.data.id
				if(flag == 0 && isFirst) {
					this.isprev = true
				}
				this.currentPage = 0
				
			},
			
			async getNovelContent(url) {
				var novelContent = await this.myApi({
					url: url
				})
				
				var nodesMsg = await _tool.getBookContent(novelContent, '<div id="content">', '<a href')
				return nodesMsg
				// this.nodes = nodesMsg
				console.log(nodesMsg)
			},
			
			// 获取行距和边距
			getLineAndPadding() {
				this.lineHeight = uni.getStorageSync('lineheight') ? uni.getStorageSync('lineheight') : this.lineHeight
				this.paddinglr = uni.getStorageSync('padding') ? uni.getStorageSync('padding') : this.paddinglr
			},
			// 获取页面高度和总页数
			calPageHeightAndCount() {
				var blank = uni.createSelectorQuery().select('.blank-view')
				blank.boundingClientRect(data => {
					this.contentHeight = Math.floor(data.height / this.lineHeight) * this.lineHeight
				}).exec();
				
				var novel = uni.createSelectorQuery().select('.read-main')
				novel.boundingClientRect(data => {
					this.totalPage = Math.ceil(data.height / this.contentHeight)
					if(this.isprev) {
						this.currentPage = this.totalPage - 1
						this.isprev = false
					}
				}).exec();
				
			},
			
			// 跳转到设置更多
			toMoreSet() {
				this.isSet = false
				uni.navigateTo({
					url: './more-set'
				})
			},
			// 跳转到目录页
			toChapter() {
				this.isSet = false
				uni.redirectTo({
					url: './chapter?nid=' + this.nid + '&currentChapter=' + this.currentChapter
				})
			},
			
			// 选择背景
			selectBg(index) {
				for (var i = 0; i < this.bgColorList.length; i++) {
					if(i == index) {
						this.bgColorList[i].checked = true
						this.bgColor = this.bgColorList[i].class
						this.bgColorPopup = this.bgColorList[i].popupclass
					} else {
						this.bgColorList[i].checked = false
					}
				}
			},
			
			// 加减字体大小
			addFontsize() {
				if(this.fontSize < 40){
					this.fontSize = this.fontSize + 2
				}
			},
			subFontsize() {
				if(this.fontSize > 28){
					this.fontSize = this.fontSize - 2
				}
			},
			
			// 设置显示
			showSet() {
				this.closePopup()
				this.isSet = true
			},
			closeSet() {
				this.isSet = false
			},
			
			
			// 右上角点击显示
			showAbout() {
				this.isAbout = this.isAbout ? false : true;
			},
			
			// 回到上个页面
			goBack() {
				uni.switchTab({
					url: '../index/index'
				})
			},
			
			// 菜单--------------------开始
			change(e) {
				this.ismenu = e.show;
			},
			closePopup() {
				// 关闭弹层
				this.$refs.buttom.close()
				this.$refs.top.close()
			},
			toggle(type1, type2) {
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.buttom.closeMask()
				this.$refs.top.closeMask()
				this.$refs.buttom.open(type1)
				this.$refs.top.open(type2)
			},
			showMenu(e) {
				// 关闭设置
				if(this.isSet){
					this.closeSet()
					return
				}
				
				// 关闭详情
				if(this.isAbout){
					this.isAbout = false
					return
				}
				
				// 关闭弹层
				if(this.ismenu) {
					this.closePopup()
					return
				}
				
				// 判断位置，且打开弹层
				var currentWidth = e.detail.x;
				var currentheight = e.detail.y;
				
				
				const showEvent = function(res) {
					// 召唤菜单点击触发的区域
					var menuWidth = (res.windowWidth - 100) / 2;
					var menuHeight = (res.windowHeight - 160) / 2;
					
					var halfWidth = (res.windowWidth) / 2;
					// 判断点击位置
					if ((currentWidth > menuWidth && currentWidth < (menuWidth + 100)) && (currentheight > menuHeight && currentheight < (menuHeight + 160))) {
						this.toggle('bottom', 'top')
					} else if(currentWidth > halfWidth) {
						// 右边
						if (this.currentPage < this.totalPage - 1) {
							this.currentPage++
						} else {
							// 下一章
							this.toPrevOrNextChapter(1)
						}
					} else {
						// 左边
						if (this.currentPage > 0) {
							this.currentPage--
						} else {
							this.toPrevOrNextChapter(0)
						}
					}

				}
				// const showEvent = function(res) {
				// 	// 允许点击触发的区域
				// 	var width = (res.windowWidth - 100) / 2;
				// 	var height = (res.windowHeight - 160) / 2;
				// 	// 判断点击位置
				// 	if ((currentWidth > width && currentWidth < (width + 100)) && (currentheight > height && currentheight < (height + 160))) {
				// 		this.toggle('bottom', 'top')
				// 	}

				// }
				uni.getSystemInfo({
					success: showEvent.bind(this)
				})
			},
			// 菜单------------------------------------------结束
			
			// 滑动翻页----------------------------------------开始
			tchStart(e) {
				
				this.startData.cliX = e.changedTouches[0].clientX;
				this.startData.cliY = e.changedTouches[0].clientY;
			},
			tchEnd(e) {
				
				var subX = e.changedTouches[0].clientX - this.startData.cliX;
				// var subY = e.changedTouches[0].clientY - this.startData.cliY;

				if (subX > 5) {
					// 向右滑，向前翻页
					if (this.currentPage > 0) {
						this.currentPage--
					} else {
						this.toPrevOrNextChapter(0)
					}
				}
				if (subX < -5) {
					// 向左滑，向后翻页
					if (this.currentPage < this.totalPage - 1) {
						this.currentPage++
					} else {
						// 下一章
						this.toPrevOrNextChapter(1)
					}
				}
			}
			// 滑动翻页--------------------------------------------结束
		}
	}
</script>

<style>
	.page-box {
		height: 100vh;
		width: 100vw;
		/* overflow: hidden; */
	}
	.novel-detail-page {
		padding-top: 50rpx;
	}

	.blank-view {
		width: 0%;
		height: 83vh;
	}

	.novel-title {
		padding: 30rpx 0;
	}

	.read-content {
		color: #1d1b1b;
		box-sizing: border-box;

		width: 100vw;
		/* height: 92vh; */

		position: absolute;
		z-index: 2;
		overflow: hidden;

	}

	.read-main {
		display: inline-block;
		position: absolute;
		/* left: 0; */
		z-index: 3;
		/* text-indent: 2em; */
	}

	.footer-view {
		display: flex;
		/* width: 100%; */
	}

	

	.menu-view {
		width: 100%;
		position: absolute;
		bottom: 0;
		z-index: 4;
		background-color: #FFB400;

	}

	.menu-box {
		width: 100%;
		height: 20vh;
	}

	.flex {
		display: flex;
		justify-content: space-around;
		text-align: center;
	}
	.flex-btw {
		display: flex;
		justify-content: space-between;
		/* text-align: center; */
		align-items: center;
	}
	.top-popup-box {
		padding-top: 50rpx;
	}
	
	.top-popup-view {
		padding: 0 20rpx;
	}
	
	
	

	.flex-column {
		display: flex;
		justify-content: center;
		flex-flow: column wrap;
	}

	.menu-word {
		margin-top: -20rpx;
	}

	.menu-chapter {
		line-height: 40px;
		padding: 10px 0;
	}
	
	.bg-white {
		background-color: #fff;
	}
	.bg-white-bd {
		border: 1rpx solid #2C405A;
	}
	.bg-white-bai {
		background-color: #F5F5F5;
	}
	
	.bg-light-yellow {
		background-color: #FAFAD2;
	}
	.bg-light-yellow-bd {
		border: 1rpx solid #FFC107;
	}
	.bg-ly-huang {
		background-color: #FFFFF0;
	}
	
	.bg-eye {
		background-color: #CCEED0;
	}
	.bg-eye-bd {
		border: 1rpx solid #00BCD4;
	}
	.bg-eye-weilan {
		background-color: #F0FFFF;
	}
	
	
	.about-box {
		/* height: 300rpx; */
		margin-top: 15rpx;
		
	}
	
	.book-small-image {
		width: 80rpx;
		height: 100rpx;
		padding-right: 25rpx;
	}
	
	.about-box-top {
		padding: 20rpx;
		border-bottom: 1rpx solid #ccc;
	}
	
	.detail-btn {
		padding: 5rpx 40rpx;
		border: 1rpx solid #ccc;
		border-radius: 40rpx;
	}
	
	.flex-btw-center {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
		text-align: center;
		align-items: center;
		padding-bottom: 10rpx;
	}
	
	.width-25 {
		width: 25%;
	}
	
	
	.set-box {
		position: fixed;
		bottom: 0;
		width: 100%;
		z-index: 5;
	}
	
	.set-box-view {
		padding: 20rpx 30rpx;
	}
	
	.bg-box {
		width: 20%;
		height: 50rpx;
		border-radius: 25rpx;
	}
	
	.add-sub {
		border: 1rpx solid #ccc;
		padding: 8rpx 60rpx;
		border-radius: 60rpx;
		font-size: 28rpx;
		font-weight: bold;
	}
	
	.font-size-show {
		padding: 0 30rpx;
	}
	
	.ctrl-btn-boxs {
		display: flex;
		align-items: center;
	}
	
	.add-shelf-btn {
		padding: 3rpx 30rpx;
		border: 1rpx solid #ccc;
		border-radius: 40rpx;
		margin-right: 40rpx;
	}
	
	
</style>
